﻿using System;
using System.Windows.Forms;

public static class TreeViewCheck
{
	public static void CheckControl(object sender, TreeViewEventArgs e)
	{
		if (e.Action != TreeViewAction.Unknown && e.Node != null && !Convert.IsDBNull(e.Node))
		{
			TreeViewCheck.CheckParentNode(e.Node);
			if (e.Node.Nodes.Count > 0)
			{
				TreeViewCheck.CheckAllChildNodes(e.Node, e.Node.Checked);
			}
		}
	}

	private static void CheckAllChildNodes(TreeNode pn, bool IsChecked)
	{
		foreach (object obj in pn.Nodes)
		{
			TreeNode treeNode = (TreeNode)obj;
			treeNode.Checked = IsChecked;
			if (treeNode.Nodes.Count > 0 && treeNode.Checked != pn.Checked)
			{
				treeNode.Checked = !treeNode.Checked;
			}
		}
	}

	private static void CheckParentNode(TreeNode curNode)
	{
		bool flag = false;
		if (curNode.Parent != null)
		{
			foreach (object obj in curNode.Parent.Nodes)
			{
				TreeNode treeNode = (TreeNode)obj;
				if (treeNode.Checked)
				{
					flag = true;
					break;
				}
			}
			if (flag)
			{
				curNode.Parent.Checked = true;
				TreeViewCheck.CheckParentNode(curNode.Parent);
				return;
			}
			curNode.Parent.Checked = false;
			TreeViewCheck.CheckParentNode(curNode.Parent);
		}
	}
}
